/**
 * Copyright 北京彩通农旗资讯有限公司 All rights reserved.
 * 北京彩通农旗资讯有限公司 专有/保密源代码,未经许可禁止任何人通过任何* 渠道使用、修改源代码.
 */
package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.LogUtil;

import java.util.ArrayList;
import java.util.List;


public class OfflineDataRecordDB extends BaseSql {

    private static final String TAG = OfflineDataRecordDB.class.getSimpleName();

    private String TableName = "OfflineDataRecord";
    private MyDBHelper helpDb;
    private SQLiteDatabase sqldb;

    public String Key = "key";//    text    否   业务key值
    public String Name = "name";//  text    否   业务名称
    public String Last_time = "last_time";//    text    否   更新时间    上一次更新时间，默认为空
    public String Status = "status";//text  是   下载状态    1：完成；0：下载中；
    public String Size = "size";//interger  否   数据库大小
    public String Path = "path";//text  否   数据库存储路径
    public String Remark1 = "remark1";//text    否   备注1
    public String Remark2 = "remark2";//text    否   备注2

    @Override
    public void create(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TableName + " (_ID INTEGER PRIMARY KEY AUTOINCREMENT," + Key + " text," + Name
                + " text," + Last_time + " text," + Status + " integer ," + Size + " text," + Path + " text," + Remark1
                + " text," + Remark2 + " text);");
    }

    public OfflineDataRecordDB() {

    }

    public void beginTransaction() {
        if (sqldb == null || !sqldb.isOpen()) {
            sqldb = helpDb.getWritableDatabase();
        }
        sqldb.beginTransaction();
    }

    public void endTransaction() {
        if (sqldb == null || !sqldb.isOpen()) {
            sqldb = helpDb.getWritableDatabase();
        }
        sqldb.setTransactionSuccessful();
        sqldb.endTransaction();
    }

    protected void checkDb() {
        if (sqldb == null || !sqldb.isOpen()) {
            sqldb = helpDb.getWritableDatabase();
        }
    }

    public void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    public String insertOrUpdate(String key, String name, int status, long size, String path) {

        ContentValues cv = new ContentValues();
        cv.put(Key, key);
        if (!TextUtils.isEmpty(name)) {
            cv.put(Name, name);
        }
        cv.put(Status, status);
        String curTime = DateUtils.getCurrentDatetimeString("");
        cv.put(Last_time, curTime);
        cv.put(Size, size);
        if (!TextUtils.isEmpty(path)) {
            cv.put(Path, path);
        }
        String[] columns = {Key, Status, Path};
        String selection = Key + "=?";
        String[] selectionArgs = new String[]{key};
//        values = cv;
//        where = Key + " = '" + key + "'";
//        int insertResult = super.saveOrUpdate(TableName);
        Cursor cur = null;
        try {
            checkDb();
            cur = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
            if (cur != null && cur.getCount() > 0) {
                //存在对应key更新
                String whereClause = Key + " =?";
                String[] whereArgs = new String[]{key};
                int result = sqldb.update(TableName, cv, whereClause, whereArgs);
                LogUtil.v(TAG, "更新离线Db数据下载记录表 key" + key + " 状态为" + status + "状态，结果为" + result + "更新时间为" + curTime);
            } else {
                long insertResult = sqldb.insert(TableName, null, cv);
                LogUtil.v(TAG, "添加离线Db数据下载记录表 key" + key + "  状态为" + status + "状态，结果为" + insertResult + "更新时间为" +
                        curTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeDbAndCursor(cur);
        }
        return curTime;
    }

    /**
     * 方法描述 : 根据对应key查询最近更新时间
     *
     * @param key
     * @return
     */
    public String queryUpdateTimeByKey(String key) {

        String[] columns = {Last_time};
        String selection = Key + "=?  and " + Status + " = 1";
        String[] selectionArgs = new String[]{key};
        String content = "";
        Cursor cursor = null;
        try {
            checkDb();
            cursor = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                if (cursor.moveToFirst()) {
                    content = cursor.getString(0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeDbAndCursor(cursor);
        }
        LogUtil.v(TAG, "queryUpdateTimeByKey Time:" + content + " key:" + key);
        return content;
    }

    /**
     * 方法描述 : 更新状态
     *
     * @return
     */
    public int updateStatus(String key, int status) {

        String whereClause = Key + " =?";
        String[] whereArgs = new String[]{key};
        ContentValues cv = new ContentValues();
        cv.put(Status, status);
        cv.put(Last_time, DateUtils.getCurrentDatetimeString(""));
        checkDb();
        int result = sqldb.update(TableName, cv, whereClause, whereArgs);
        LogUtil.v(TAG, "更新离线Db数据下载记录表 状态为" + status + "状态，结果为" + result + "更新时间为");
        return 0;
    }

    /**
     * 保存日志提交成功的记录表
     *
     * @param name 固定为commit_log_record
     * @param status 下载状态 1：完成；0：下载中；
     *
     * @return
     */
    public List<String> queryKeyByName(String name, String status) {

        List<String> logIdList = new ArrayList<String>();
        String[] columns = {Key};
        String selection = Name + "=?  and " + Status + " = ?";
        String[] selectionArgs = new String[]{name, status};
        String content = "";
        Cursor cursor = null;
        try {
            checkDb();
            cursor = sqldb.query(TableName, columns, selection, selectionArgs, null, null, null);
            if (cursor != null && cursor.getCount() > 0) {
                if (cursor.moveToNext()) {
                    content = cursor.getString(0);
                    logIdList.add(content);
                }
                LogUtil.v(TAG, "queryUpdateTimeByKey Time:" + logIdList.toString() + " name:" + name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeDbAndCursor(cursor);
        }

        return logIdList;
    }

    public void deleteAllRows() {
        checkDb();
        int result = sqldb.delete(TableName, null, null);
        LogUtil.v(TAG, "OfflineDataRecordDB DeleteAllRows result:" + result);
    }

    public void dropTable(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + TableName);
    }

    public OfflineDataRecordDB(MyDBHelper db) {
        super(db);
        helpDb = db;
    }

    @Override
    public void upgrade(SQLiteDatabase arg0) {

    }
}
